package com.wlstock.funi.dialog;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wlstock.funi.R;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.dao.SelfFundTagDao;
import com.wlstock.funi.dao.StockBaseInfoDao;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.runnable.OrderBuy;
import com.wlstock.funi.runnable.OrderListener;
import com.wlstock.funi.runnable.ZXRealPrice;
import com.wlstock.funi.runnable.ZXRealPrice.PriceListener;
import com.wlstock.funi.ui.FundBaseActivity;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.IntentContants;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.TimeUtils;
import com.wlstock.funi.utils.ToastUtils;

import java.util.List;

public class PopTradeDialog extends FundBaseActivity implements OnClickListener, PriceListener, OrderListener {
	
	private TextView ed_curprice;
	private EditText ed_money;
	private EditText ed_pty;
	private TextView tv_trade_type;
	private int tradeType;
	private float tradeMoney;
	private float tradePrice;
	private int tradeQty;
	private String stkCode;
	private String stkName;
	
	private TextView tv_trademoney;
	private TextView tv_trade_qty;
	
	boolean changeMoney = true;
	boolean changeQty = true;
	private int popMode;
	private ImageView img_tv_k_line;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_trade);
		
		Intent intent = getIntent();
		if (intent!=null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				
				stkCode = bundle.getString(IntentContants.INTENT_STKCODE,"");
				stkName = bundle.getString(IntentContants.INTENT_STKNAME);
				
				if (stkName == null) {
					stkName = StockBaseInfoDao.getInstance(this).queryName(stkCode);
				}
				tradeType = bundle.getInt(IntentContants.INTENT_TRADE_TYPE, -1);
				tradePrice = bundle.getFloat(IntentContants.INTENT_CUR_PRICE, 0.1F);
				tradeMoney = bundle.getFloat(IntentContants.INTENT_TRADE_MONEY, 0.1F);
				tradeQty = bundle.getInt(IntentContants.INTENT_TRADE_QTY, -1);
				popMode = bundle.getInt(IntentContants.INTENT_POP_MODE,IntentContants.INTENT_POP_MODE_SIMPLE);
			}
		}
		
		if (SelfFundDao.getInstance(this).querySelfFundModel(stkCode) == null) {
			Button btn_add_sf = (Button) findViewById(R.id.btn_add_sf);
			btn_add_sf.setVisibility(View.VISIBLE);
			btn_add_sf.setOnClickListener(this);
		}
		
		tv_trade_type = (TextView) findViewById(R.id.tv_trade_type);
		
		tv_trademoney = (TextView) findViewById(R.id.tv_trademoney);
		tv_trade_qty = (TextView) findViewById(R.id.tv_trade_qty);
		
		if (tradeType!=-1) {
			if (tradeType==OperateModel.TradeType_BUY) {
				tv_trademoney.setText("买入金额:");
				tv_trade_type.setText("买入"+stkName+"("+stkCode+")");
				tv_trade_qty.setText("买入数量");
			}else if(tradeType==OperateModel.TradeType_SELL){
				tv_trademoney.setText("卖出金额:");
				tv_trade_type.setText("卖出"+stkName+"("+stkCode+")");
				tv_trade_qty.setText("卖出数量");
			}
		}
		
		ed_curprice = (TextView) findViewById(R.id.ed_curprice);
		findViewById(R.id.btn_refresh).setOnClickListener(this);
		if(tradePrice!=0.1f){
			ed_curprice.setText(String.valueOf(tradePrice));	
		}
		
		ed_money = (EditText) findViewById(R.id.ed_money);
		findViewById(R.id.btn_money_defautl).setOnClickListener(this);
		if (tradeMoney!=0.1f) {
			ed_money.setText(String.valueOf(tradeMoney));
			ed_money.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				}
				
				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				}
				
				@Override
				public void afterTextChanged(Editable arg0) {
					if (changeMoney) {
						try {
							changeQty = false;
							changeMoney = true;
							ed_pty.setText(String.valueOf(CaculateUtils.caculateNums(Float.valueOf(arg0.toString()), tradePrice)));
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					
				}
			});
			ed_money.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View arg0, boolean isFocus) {
					changeQty = !isFocus;
					changeMoney = isFocus;
				}
			});
		}
		
		ed_pty = (EditText) findViewById(R.id.ed_pty);
		findViewById(R.id.btn_pty_defautl).setOnClickListener(this);
		if (tradeQty != -1 ) {
			ed_pty.setText(String.valueOf(tradeQty));
			ed_pty.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {	
				}
				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {	
				}
				@Override
				public void afterTextChanged(Editable arg0) {
					if (changeQty) {
						try {
							changeQty = true;
							changeMoney = false;
							ed_money.setText(Float.valueOf(arg0.toString())*tradePrice+"");
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					
				}
			});
			
			ed_pty.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View arg0, boolean isFocus) {
					changeMoney = !isFocus;
					changeQty = isFocus;
				}
			});
		}
		
		img_tv_k_line = (ImageView) findViewById(R.id.img_tv_k_line);
		if (popMode == IntentContants.INTENT_POP_MODE_SIMPLE) {
			showImg(false);
		}else if (popMode == IntentContants.INTENT_POP_MODE_IMG) {
			if (stkCode!=null) {
				showImg(true);
			}
		}
		
		findViewById(R.id.btn_confirm).setOnClickListener(this);
		findViewById(R.id.btn_cancel).setOnClickListener(this);
	}

	private void showImg(boolean isImgShow) {
		if (isImgShow) {
			img_tv_k_line.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(StockUtils.getSinaDayKUrl(stkCode), img_tv_k_line);
		}else {
			img_tv_k_line.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			int curBSFlag = ZXRealPrice.BSFLAG_BUY;
			if (tradeType!=-1) {
				if (tradeType==OperateModel.TradeType_BUY) {
					curBSFlag = ZXRealPrice.BSFLAG_BUY;
				}else if(tradeType==OperateModel.TradeType_SELL){
					curBSFlag = ZXRealPrice.BSFLAG_SAILE;
				}
			}
			ZXRealPrice getCurrentStockPrice = new ZXRealPrice(curBSFlag, stkCode);
			getCurrentStockPrice.pListener = this;
			getCurrentStockPrice.request();
			break;
		case R.id.btn_money_defautl:
			
			break;
		case R.id.btn_pty_defautl:
			
			break;
		case R.id.btn_confirm:
			if (tradeType==OperateModel.TradeType_BUY) {
				OrderBuy buy = new OrderBuy(stkCode, stkName, Float.valueOf(ed_curprice.getText().toString()), Long.valueOf(ed_pty.getText().toString()));
				buy.buy(this);
			}else if (tradeType==OperateModel.TradeType_SELL) {
				
			}
			break;
		case R.id.btn_cancel:
			this.finish();
			break;
		case R.id.btn_add_sf:
			final String[] tagNames = SelfFundTagDao.getInstance(this).queryAllTagNames();
			if (tagNames!=null) {
				new AlertDialog.Builder(this).setTitle("选择标签").setItems(tagNames, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int which) {
						SelfFundDao.getInstance(PopTradeDialog.this).addOrUpdateSelfModel(stkCode,stkName,tagNames[which]);
					}
				}).setNegativeButton("取消",null).show();	
			}else {
				SelfFundDao.getInstance(this).addOrUpdateSelfModel(stkCode,stkName,SelfFundModel.TAG_DEFAULT);
			}
			break;
		default:
			break;
		}
		
	}
	
	@Override
	public void onUpdatePriceSuccess(List<String> priList) {
		// TODO Auto-generated method stub
		if (priList==null) {
			ToastUtils.showMiddleMsg(this, "获取最新价格失败");
			return;
		}
		for (String string : priList) {
			ToastUtils.showMiddleMsg(this, string);
		}
	}


	@Override
	public void orderSuccess(int tradeType, String stkcode, String stkName, float price, long qty) {
		if (tradeType == OperateModel.TradeType_BUY){
			NotiUtils.showSimpleNoti(this, NotiIdGenerator.ID_WILL_BUY, "真实帐号以" + ed_curprice.getText().toString() + "买入" + stkName, stkCode + "成功。  时间:" + TimeUtils.getCurrentHHMM(), R.drawable.ic_buy);
		}
	}

	@Override
	public void orderFaile(int tradeType, String stkcode, String stkName, float price, long qty, String info) {
		if (tradeType == OperateModel.TradeType_BUY){
			NotiUtils.showSimpleNoti(this, NotiIdGenerator.ID_WILL_BUY, "真实帐号以" + ed_curprice.getText().toString() + "买入" + stkName, stkCode + "失败。  时间:" + TimeUtils.getCurrentHHMM(), R.drawable.ic_buy);
		}
	}
}
